<?php
/**
 * 业务处理基类
 *
 * @author 孙晓晔
 * @version $Id: AdminUtil.class.php 1052 2010-04-07 09:05:23Z sunxy $
 */
require_once(APP_LIB . 'Util.class.php');

class AdminUtil extends Util {
	var $dsn_r;				// 定义读数据源
	var $dsn_w;				// 定义写数据源
	var $dsn_fy;			// 定义fy数据源
	
	var $num_s = '2';

	var $count = 1;
	var $result = array();
	
	var $tj;
	
	public $email = "system@tecmold.com";
	
	public $zjm = "ajax_zjm";
	
	public $orderby = array();
	public $groupby = array();
	
	public $day = array(
		'-' => '请选择',
		'3' => '3天',
		'7' => '7天',
		'15' => '15天',
		'30' => '30天',
	
		'60' => '60天',
		'90' => '90天',
		'180' => '180天',
	);
	
	public $office = array(
		'-' => '请选择',
		'1' => '深圳',
		'2' => '东莞',
	
		'9' => '其它',
	);

	/**
	 * 洲
	 */
	public $continent = array(
		'-' => '请选择',
		'1' => '亚洲',
		'2' => '欧洲',
		'3' => '美洲',	
		'4' => '非洲',
		'5' => '大洋洲',	
	);

	public $filename_option = array(
		'-' => '请选择',
		'safe' => '安全',
		'real' => '原名',
		'uniq' => '唯一',
	);

	public $star_option = array(
		'-' => '请选择',
		'1' => '一星',
		'2' => '二星',
		'3' => '三星',
		'4' => '四星',
		'5' => '五星',
	);
	
	public $currency = array(
		'-' => '请选择',
		'CNY' => '人民币',
		'HKD' => '港币',
		'USD' => '美元',
		'EUR' => '欧元',
		'GBP' => '英镑',
		'AUD' => '澳元',
		
		'JPY' => '日元',
	);
	
	public $mime = array (
			//applications
			'ai'    => 'application/postscript',
			'eps'   => 'application/postscript',
			'exe'   => 'application/octet-stream',
			
			'doc'   => 'application/vnd.ms-word',
			'xls'   => 'application/vnd.ms-excel',
			
			'docx'   => 'application/vnd.ms-word',
			'xlsx'   => 'application/vnd.ms-excel',
			
			'ppt'   => 'application/vnd.ms-powerpoint',
			'pps'   => 'application/vnd.ms-powerpoint',
			'pdf'   => 'application/pdf',
			'xml'   => 'application/xml',
			'odt'   => 'application/vnd.oasis.opendocument.text',
			'swf'   => 'application/x-shockwave-flash',
			// archives
			'gz'    => 'application/x-gzip',
			'tgz'   => 'application/x-gzip',
			'bz'    => 'application/x-bzip2',
			'bz2'   => 'application/x-bzip2',
			'tbz'   => 'application/x-bzip2',
			'zip'   => 'application/zip',
			'rar'   => 'application/x-rar',
			'tar'   => 'application/x-tar',
			'7z'    => 'application/x-7z-compressed',
			// texts
			'txt'   => 'text/plain',
			'php'   => 'text/x-php',
			'html'  => 'text/html',
			'htm'   => 'text/html',
			'js'    => 'text/javascript',
			'css'   => 'text/css',
			'rtf'   => 'text/rtf',
			'rtfd'  => 'text/rtfd',
			'py'    => 'text/x-python',
			'java'  => 'text/x-java-source',
			'rb'    => 'text/x-ruby',
			'sh'    => 'text/x-shellscript',
			'pl'    => 'text/x-perl',
			'sql'   => 'text/x-sql',
			// images
			'bmp'   => 'image/x-ms-bmp',
			'jpg'   => 'image/jpeg',
			'jpeg'  => 'image/jpeg',
			'gif'   => 'image/gif',
			'png'   => 'image/png',
			'tif'   => 'image/tiff',
			'tiff'  => 'image/tiff',
			'tga'   => 'image/x-targa',
			'psd'   => 'image/vnd.adobe.photoshop',
			//audio
			'mp3'   => 'audio/mpeg',
			'mid'   => 'audio/midi',
			'ogg'   => 'audio/ogg',
			'mp4a'  => 'audio/mp4',
			'wav'   => 'audio/wav',
			'wma'   => 'audio/x-ms-wma',
			// video
			'avi'   => 'video/x-msvideo',
			'dv'    => 'video/x-dv',
			'mp4'   => 'video/mp4',
			'mpeg'  => 'video/mpeg',
			'mpg'   => 'video/mpeg',
			'mov'   => 'video/quicktime',
			'wm'    => 'video/x-ms-wmv',
			'flv'   => 'video/x-flv',
			'mkv'   => 'video/x-matroska'
	);
	
	public $visible = array(
		'-' => '请选择',
		
		'1' => '否',
		'2' => '是',
			
		// '9' => '其它',
	);

	/**
	 * 状态
	 */
	public $status = array(
		'-' => '请选择',
		'1' => '已开通',
		'2' => '未开通',
	
		'9' => '其它',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/03/03 07:24:42 $';
		$request['revision'] = '$Revision: 1.5 $';
			
		parent::__construct($request);

		$this->dsn = 'ydt';
		$this->dsn_r = 'ydt';
		$this->dsn_w = 'ydt';
	}

	/**
	 * 预处理
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function pretreat($controller) {
		
		$controller->assign_by_ref('orderby_option', $this->orderby);
		$controller->assign_by_ref('groupby_option', $this->groupby);
		
		$controller->assign('day_option', $this->day);
		$controller->assign_by_ref('office_option', $this->office);		
		$controller->assign_by_ref('continent_option', $this->continent);		
		$controller->assign_by_ref('filename_option', $this->filename_option);
		$controller->assign_by_ref('star_option', $this->star_option);
		
		$controller->assign_by_ref('visible_option', $this->visible);

		$controller->assign_by_ref('status_option', $this->status);		

		$desc = array(
			'-' => '请选择',
			'1' => '按升序',
			'2' => '按降序',
		);
		$controller->assign('desc_option', $desc);
		
		$pagesize = array(
			'-' => '请选择',
			'10' => '10',
			'15' => '15',
			'20' => '20',
			'50' => '50',
			'100' => '100',
			'200' => '200',
			'500' => '500',
		);
		$controller->assign('pagesize_option', $pagesize);
		
		$controller->assign_by_ref('currency', json_encode($this->currency));		
		$controller->assign_by_ref('currency_option', $this->currency);
				
		$dd = $this->_dd_option();
		$controller->assign_by_ref('dd_option', $dd);
		// $controller->assign('t1', strtotime('-1 YEAR'));
		
		$controller->assign_by_ref('t', $this->t);
	}

	public $t = array(
		'id'=>'请输入信息的流水号或多个信息的流水号，用逗号分开，如123或123,124,126',
		'customer'=>'请输入客户编号，然后选择并回车即可，如GM822或822',
		'supplier'=>'请输入供应商名称拼音首字母，然后选择并回车即可。如鸿盛，输入hs',
		'dept'=>'请输入部门名称拼音首字母，然后选择并回车即可。如行政，输入xz',
		'mold'=>'请输入产品编号，然后选择并回车即可。如GM822.209或822.209',
		'engineer'=>'请输入工程师姓名拼音首字母，然后选择并回车即可。如李四，输入ls；若为离职人员，请输入3ls',
		'quote'=>'直接输入项目编号即可，如GM822.209',
		'emp'=>'请输入员工姓名拼音首字母，然后选择并回车即可，如李四，输入ls；若为离职人员，请输入3ls',
		'emp_'=>'请输入%s姓名拼音首字母，然后选择并回车即可，如李四，输入ls；若为离职人员，请输入3ls',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		''=>'',
		
	);
	
	function _dd_option() {
		$t1 = strtotime("-13 month");
		$t2 = time();

		$arr = array('-'=>'请选择');
		while ($t1 < $t2) {
			$str = date("Y-m", $t2);
			$t2 = strtotime("-1 month", $t2);

			$arr[$str] = $str;
		}

		return $arr;
	}
	
	function pretreat_group($controller) {
		$this->pretreat($controller);

		$orderby = array(
			'-' => '请选择',
			'1' => '按分类',
			'2' => '按数值',
		);
		$controller->assign('orderby_option', $orderby);

		$desc = array(
			'-' => '请选择',
			'1' => '按升序',
			'2' => '按降序',
		);
		$controller->assign('desc_option', $desc);
		
		// $controller->assign('t1', strtotime('-1 YEAR'));
	}

	/**
	 * 生成查询串
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function query($controller, $request) {
		$p2 = '';
		// reset($_REQUEST);
		while (list($k, $v) = each($_POST)) {
			if (empty($v) || $v == '-') {
			// if (strlen($v) == 0 || $v == '-') {
				continue;
			}

			if ($this->not_query($k)) {
				continue;
			}
			
			$tmp = '';
			if (is_array($v)) {
				while (list($a, $b) = each($v)) {
					$tmp .= sprintf("&%s[]=%s", $k, $b);
				}
				$p2 .= $tmp;
			} else {
				$p2 .= '&' . $k . '=' . $v;
			}
			$controller->assign($k, $v);
		}

		while (list($k, $v) = each($_GET)) {
			if (empty($v) || $v == '-') {
			// if (strlen($v) == 0 || $v == '-') {
				continue;
			}

			if ($this->not_query($k)) {
				continue;
			}

			$tmp = '';
			if (is_array($v)) {
				while (list($a, $b) = each($v)) {
					$tmp .= sprintf("&%s[]=%s", $k, $b);
				}
				$p2 .= $tmp;
			} else {
				$p2 .= '&' . $k . '=' . $v;
			}
			
			$controller->assign($k, $v);
		}

		$controller->assign('p2', $p2);

		return $p2;
	}

	/**
	 * 判断是否是查询选项
	 *
	 * @param string $s
	 * @return boolean
	 */
	function not_query($s) {
		if (empty($s)) {
			return true;
		}

		if (substr($s, -2) == '_s') {
			return false;
		}

		$kk = array('id', 'status', 'code', 'r0', 'r1', 'r2');
		if (in_array($s, $kk)) {
			return false;
		}

		return true;
	}
	
	function _orderby($default = "id") {
		if (empty($this->orderby_s) || $this->orderby_s == '-') {
			$orderby = $default;
		}

		if ($this->orderby_s == '1') {
			$orderby = "id";
		}

		if ($this->orderby_s == '2') {
			$orderby = "modifytime";
		}
		
		if (empty($orderby)) {
			$orderby = $this->orderby_s;
		}

		$fmt = " ORDER BY %s %s";
		$ret = sprintf($fmt, $orderby, $this->desc);

		return $ret;
	}

	/**
	 * 构造一个SQL的groupby
	 *
	 * @param string $px
	 * @param array $orderby
	 * @param string $default
	 * @return string
	 */
	function groupby_aa($px, $groupby, $default) {
		if (empty($px) || $px == '-') {
			return $default;
		}

		if (!array_key_exists($px, $groupby)) {
			return $default;
		}

		return $px;
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(createtime, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(createtime, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(createtime, '%Y-%m')";
		}
		
		if ($px == '4') {
			return "DATE_FORMAT(createtime, '%Y')";
		}

		return $px;
	}

	/**
	 * 参数保存
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPara($controller, $request) {
		$p2 = $this->query($controller, $request);

		if (!empty($request['p'])) {
			$p2 .= '&p=' . $request['p'];
			$controller->assign('p', $request['p']);
		}
		$controller->assign('p3', $p2);

		$this->orderby_s = $request['orderby_s'];
		$this->desc_s = $request['desc_s'];

		if ($this->desc_s == '1') {
			$this->desc = "";
		} else {
			$this->desc = " DESC";
		}
	}
	
	function _where_dept($emp) {
		require_once(dirname(__FILE__) . '/info/DeptEmp.class.php');
		$aa = new DeptEmp();
		
		return $aa->_dept($emp);
	}

	/**
	 * 构造一个固定SQL语句中的where
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function _where_default($request) {
		$id_s = $request['id_s'];
		
		$customer_s = $this->_input($request['customer_s']);
		$project_s = trim($request['project_s']);
		$mold_s = $this->_input($request['mold_s']);
		
		$supplier_s = $this->_input($request['supplier_s']);
		$currency_s = $request['currency_s'];
		
		$visible_s = $request['visible_s'];
		
		$office_s = $request['office_s'];
		$dept_s = $this->_input($request['dept_s']);
				
		$emp_s = $this->_input($request['emp_s']);
		$oper_s = $this->_input($request['oper_s']);
		
		$t1_s = $request['t1_s'];
		$t2_s = $request['t2_s'];
		
		$time_c = $request['time_c_s'];

		$where = '';
		if (!empty($id_s)) {
			// $where .= " AND a.id = '" . $id_s . "'";
			$where .= $this->_id_s($id_s);
		}
		
		if (!empty($customer_s)) {
			$where .= " AND customer = '" . $customer_s . "'";
		}
		
		if (!empty($project_s)) {
			$where .= " AND project = '" . $project_s . "'";
		}
		
		if (!empty($mold_s)) {
			$where .= " AND mold = '" . $mold_s . "'";
		}
		
		if (!empty($supplier_s)) {
			$where .= " AND supplier = '" . $supplier_s . "'";
		}
		
		$where .= $this->_where_x("currency", $request['currency_s']);
		/*
		if (!empty($currency_s) && $currency_s <> '-') {
			$where .= " AND currency = '" . $currency_s . "'";
		}*/
		
		$where .= $this->_where_status($request['status_s']);		
				
		if (!empty($office_s) && $office_s <> '-') {
			$where .= " AND office = '" . $office_s . "'";
		}
		
		if (!empty($dept_s) && $dept_s <> '-') {
			$where .= " AND dept LIKE '" . $dept_s . "%'";
		}
		
		if (!empty($emp_s) && $emp_s <> '-') {
			$where .= " AND emp = '" . $emp_s . "'";
		}
		
		if (!empty($oper_s) && $oper_s <> '-') {
			$where .= " AND oper = '" . $oper_s . "'";
		}
		
		if (strlen($visible_s) > 0 && $visible_s <> '-') {
			$where .= " AND visible = '" . $visible_s . "'";
		}
		
		if (empty($time_c) || $time_c == 'create') {
			if (!empty($t1_s)) {
				$where .= " AND a.createtime > '" . $t1_s . "'";
			}
	
			if (!empty($t2_s)) {
				$where .= " AND a.createtime < '" . $t2_s . "'";
			}
			
			$dd_s = $request['dd_s'];
			
			if (!empty($dd_s)) {
				$where .= " AND DATE_FORMAT(a.createtime, '%Y-%m-%d') = '" . $dd_s . "'";
			}
		} else {		
			if (!empty($t1_s)) {
				$where .= " AND a.modifytime > '" . $t1_s . "'";
			}
	
			if (!empty($t2_s)) {
				$where .= " AND a.modifytime < '" . $t2_s . "'";
			}
		}

		return $where;
	}
	
	function _where_status($s) {
		return $this->_where_x('a.status', $s);
	}
	
	function _where_x($f, $s) {
		if (is_array($s)) {
			$a = array();
			while (list($k, $v) = each($s)) {
				if ($v == '-') {
					continue;
				}
				
				$a[] = "'" . $v . "'";
			}
			
			if (count($a) == 0) {
				return '';
			}
			
			return sprintf(" AND %s IN (%s)", $f, implode(",", $a));
		}
		
		if (!empty($s) && $s <> '-') {
			return sprintf(" AND %s = '%s'", $f, $s);
		}
		
		return '';
	}
	
	function _id_s($id_s) {
		
		return $this->_x_s("a.id", $id_s);
	}
	
	function _x_s($x, $v) {
		
		$v = trim($v, "\s,|:|\\,");
		$a = preg_split("/[\s,|:|\\,]/i", $v);
		if (count($a) > 1) {
			$s = implode(", ", $a);
			
			return sprintf(" AND %s IN (%s)", $x, $s);
		}
		
		return sprintf(" AND %s = '%s'", $x, $v);
	}

	/**
	 * SQL语句中的无用查询条件删除
	 *
	 * @param string $where
	 * @return string
	 */
	function _where_aa($where) {
		if (trim($where) == 'WHERE 1=1') {
			return '';
		}

		return str_replace('1=1 AND', '', $where);
	}

	/**
	 * 参数保存
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPara_($controller, $request) {
		$this->findPara($controller, $request);
	}

	function groupPara($controller, $request) {
		$this->findPara($controller, $request);

		$this->result_s = $request['result_s'];

		$this->groupby_s = $request['groupby_s'];
		$this->orderby_s = $request['orderby_s'];
		$this->desc_s = $request['desc_s'];

		$this->num_s = $request['num_s'];

		$this->s = $this->groupby($controller, $this->groupby_s);

		if ($this->orderby_s == '1') {
			$this->orderby = $this->s;
		} else {
			$this->orderby = "c";
		}

		if ($this->desc_s == '1') {
			$this->desc = "";
		} else {
			$this->desc = "DESC";
		}
	}

	function admin2($controller, $request) {
		global $CategoryTree;

		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE code LIKE '__' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept);
		// debug($sql);
		$result = $db->query($sql);
		// $data = array('class'=>'Opened');
		$data = array();
		$data['查找'] = array('ee'=>'/t/portal/?do=Address.find', 'js'=>'');
		$data['部门'] = array('dd'=>'/t/portal/?do=Address.tab', 'js'=>'');
		while ($row = $db->fetch_array($result)) {
			$name = $row['name'];
			$data[$name] = $this->_book_dept($row);
		}
		
		// debug(print_r($data, true));

		$CategoryTree["通讯录"] = $data;
		
		// debug(print_r($CategoryTree, true));

		$MenuTree = $this->tree($_SESSION['name'], $CategoryTree);
		$controller->assign('MenuTree', $MenuTree);

		// print_r($_SESSION['mytree']);

		$controller->display($request, 'admin');
		return true;
	}
	
	function admin($controller, $request) {
		global $CategoryTree, $cfg;
		
		$workerman = $cfg['workerman']['root'];
		
		$workerman['url'] = sprintf("ws://%s:%s", $workerman['host'], $workerman['port']);
		
		$controller->assign_by_ref('workerman', $workerman);

		$MenuTree = $this->tree($_SESSION['name'], $CategoryTree);
		$controller->assign('MenuTree', $MenuTree);

		$controller->display($request, 'admin');
		return true;
	}

	function _book_dept($row) {
		$db = newdb(Constant::tbl_dept);
		$fmt = "SELECT * FROM %s WHERE code LIKE '%s__' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_dept, $row['code']);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			return array('ee'=>'/t/portal/?do=Address.view&dept=' . $row['code'], 'js'=>'');
		}

		$data = array();
		// $data['全部'] =  array('bb'=>'/t/portal/?do=Address.view&dept=' . $row['code'], 'js'=>'');
		while ($row = $db->fetch_array($result)) {
			$name = $row['name'];
			$data[$name] = $this->_book_dept($row);
		}

		return $data;
	}
	
	var $_tab = 0;

	/**
	 * 生成一个树型结构的菜单
	 *
	 * @param string $title
	 * @param array $data
	 */
	function tree($title, $data) {
		$class = "Closed";
		if (array_key_exists("class", $data)) {
			$class = $data['class'];
		}
			
		$ret = "<li class=\"$class\"><img class=s src=\"/images/s.gif\" onclick=\"menutree(this);\"><a href=\"javascript:void(0)\" onclick=\"menutree(this);\">$title</a>
    <ul>\n";

		$submenu = '';
		foreach ($data as $k => $v) {
			if ($k == 'class') {
				continue;
			}

			$submenu = $this->_tree($submenu, $k, $v);
			/*
			 if ($k == "退出") {
				$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"$v\">$k</a></li>\n";
				} elseif (array_key_exists('dd', $v)) {
				$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['dd'] . "', '#placeholder')\">$k</a></li>\n";
				} elseif (array_key_exists('cc', $v) && $this->tree_my($v)) {
				$submenu .= "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['cc'] . "', '#placeholder')\">$k</a></li>\n";
				} elseif (is_array($v)) {
				$submenu .= $this->tree($k, $v);
				}*/
		}

		if (empty($submenu)) {
			return '';
		}

		$ret .= $submenu . "</ul>
  </li>\n";

		return $ret;
	}

	function _tree($submenu, $k, $v) {
		if ($k == "退出") {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"$v\">$k</a></li>\n";
		}

		if (!is_array($v)) {
			return $submenu;
		}

		if (array_key_exists('dd', $v)) {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['dd'] . "', '#placeholder')\">$k</a></li>\n";
		}
		
		if (array_key_exists('ee', $v)) {
			$this->_tab += 3;
			$fmt = "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"tab22('%s', '%s', '%s', '%s')\">%s</a></li>\n";
			return $submenu . sprintf($fmt, $v['ee'], '#placetab', $this->_tab, $k, $k);
		}
			
		if (array_key_exists('cc', $v) && $this->tree_my($v)) {
			return $submenu . "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"menu('" . $v['cc'] . "', '#placeholder')\">$k</a></li>\n";
		}
		
		if (array_key_exists('tt', $v) && $this->tree_my($v)) {
			$this->_tab += 3;
			$fmt = "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"tab('%s', '%s', '%s', '%s')\">%s</a></li>\n";
			return $submenu . sprintf($fmt, $v['tt'], '#placetab', $this->_tab, $k, $k);
		}
		
		if (array_key_exists('bb', $v) && $this->tree_my($v)) {
			$this->_tab += 3;
			$fmt = "<li class=\"Child\"><img class=s src=\"/images/s.gif\"><a href=\"javascript:void(0)\" onClick=\"tab22('%s', '%s', '%s', '%s')\">%s</a></li>\n";
			return $submenu . sprintf($fmt, $v['bb'], '#placetab', $this->_tab, $k, $k);
		}
			
		return $submenu . $this->tree($k, $v);
	}

	/**
	 * 判断是否有权限
	 *
	 * @param string $v
	 * @return boolean
	 */
	function tree_my($v) {
		if ($_SESSION['name'] == "admin") {
			return true;
		}
		
		if ($_SESSION['admin'] == "8") {
			return true;
		}
		
		if (!is_array($_SESSION['mytree'])) {
			return false;
		}

		reset($_SESSION['mytree']);
		while (list($k, $b) = each($_SESSION['mytree'])) {
			// debug("b = " . $b . ", cc = " . $v['cc']);
			$b = quotemeta($b);
			if (preg_match("/$b/", $v['cc'])) {
				return true;
			}
		}

		$public_action = Common::action();
		while (list($k, $b) = each($public_action)) {
			// debug("b = " . $b . ", cc = " . $v['cc']);
			$b = quotemeta($b);
			if (preg_match("/$b/", $v['cc'])) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 导入
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function import($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'import');
		return true;
	}

	/**
	 * 删除
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}

			$fmt = "DELETE FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			// debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 * 获取数据库时间
	 *
	 * @param string $i
	 */
	function time($i) {
		$db = newdb($this->dsn_r);
		$sql = "SELECT DATE_ADD(now(), INTERVAL $i month) t";
		// debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
			
		return strtotime($row['t']);
	}

	/**
	 * 部门员工
	 *
	 * @param string $dept
	 * @return array
	 */
	function emp_dept($dept) {
		$db = newdb(Constant::tbl_emp);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND dept LIKE '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, $dept . "%");
		// debug($sql);
		$result = $db->query($sql);

		$ret = array('-'=>'请选择');
		while($row = $db->fetch_array($result)) {
			$ret[$row['id']] = $row['name'];
		}

		return $ret;
	}

	/**
	 * 被我领导的同事
	 *
	 * @param string $field
	 * @return string
	 */
	function leader_my($field) {
		
		if ($this->_is_admin()) {
			return '';
		}

		return $field . $this->leader($_SESSION['id']);
	}

	/**
	 * 指定领导的部下
	 *
	 * @param integer $emp
	 * @return string
	 */
	function leader($emp) {
		$key = "leader_" . $emp;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (!empty($ret)) {
				return $ret;
			}
		}

		$a = array();
		$a[] = $emp;
		$db = newdb(Constant::tbl_emp_leader);
		$fmt = "SELECT * FROM %s WHERE leader = '%s' AND status = '1'";
		$sql = sprintf($fmt, Constant::tbl_emp_leader, $emp);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$a[] = $row['emp'];
		}
		
		$ret = implode(",", $a);

		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	/**
	 * 发送邮件
	 *
	 * @param string $from
	 * @param string $to
	 * @param string $subject
	 * @param string $body
	 */
	function sendmail($from, $to, $subject, $body) {
		if (empty($from) || empty($to)) {
			return;
		}
		
		if (empty($subject) || empty($body)) {
			return;
		}
		
		$header = "From: " . $from . "\n";		
		$header .= "Content-Type: text/plain; charset=utf-8\n";
		$header .= "Content-Transfer-Encoding: base64";

		$subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
		$body = chunk_split(base64_encode($body));

		mail($to, $subject, $body, $header);
	}

	function mail_html2($from, $to, $subject, $body, $cc = '') {
		echo "Sendmail...\n";

		$header = "From: " . $from . "\n";
		
		if (!empty($cc)) {
			$header .= "Cc: " . $cc ."\n";
		}

		$header .= "Content-Type: text/html; charset=utf-8\n";
		$header .= "Content-Transfer-Encoding: base64";

		$subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
		$body = chunk_split(base64_encode($body));

		mail($to, $subject, $body, $header);
	}
	
	function mail_html($from, $to, $subject, $body) {
		if (empty($from) || empty($to)) {
			return;
		}
		
		if (empty($subject) || empty($body)) {
			return;
		}
		
		require_once('Mail.php');
		require_once('Mail/mime.php');
		
		$headers['From'] = $from;
		$headers['Subject'] = "=?UTF-8?B?".base64_encode($subject)."?=";
				
		$mime = new Mail_mime("\n");		
		$mime->setHTMLBody($body);
				
		$param = array(
			"head_encoding" => "base64",
			"text_encoding" => "base64",
			"html_encoding" => "base64",
			"head_charset" => "utf-8",
			"text_charset" => "utf-8",
			"html_charset" => "utf-8",			
		);
		
		$body = $mime->get($param);
		$headers = $mime->headers($headers);
		$headers['Content-Type'] = 'text/html; charset=utf-8';		

		// print_r($headers);
		
		$message = & Mail::factory('mail');
		$message->send($to, $headers, $body);
	}

	/**
	 * 清除空目录
	 *
	 * @param string $file
	 * @return boolean
	 */
	function dir_clean($file) {
		if (is_file($file)) {
			$dir = dirname($file);
		} else {
			$dir = $file;
		}

		if ($this->dir_empty($dir)) {
			rmdir($dir);

			return $this->dir_clean(dirname($dir));
		}

		return true;
	}

	/**
	 * 判断目录是否为空
	 *
	 * @param String $dir
	 * @return boolean
	 */
	function dir_empty($dir) {
		$dh = opendir($dir);
		while (($file = readdir($dh)) !== false) {
			if ($file == '.' || $file == '..') {
				continue;
			}
			closedir($dh);

			return false;
		}

		closedir($dh);

		return true;
	}

	/**
	 * 状态更新
	 *
	 * @param string $tbl
	 * @param integer $id
	 * @param integer $status
	 */
	function _status($tbl, $id, $status) {
		clean($this->tbl . "_id_" . $id);

		$db = newdb($tbl);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $tbl, $status, $id);
		// debug($sql);
		$db->query($sql);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_barcode($controller, $request) {
		$s = $request['s'];

		require_once 'Image/Barcode.php';
		Image_Barcode::draw($s, 'code128', 'png');

		return true;
	}

	function _input($s) {
		if (empty($s)) {
			return '';
		}
		
		$s = trim($s);

		$a = preg_split("/[\s,|:|\\,]/i", $s);
		if (count($a) > 1) {
			return $a[0];
		}

		return $s;
	}

	/**
	 * 权限判断
	 */
	function audit($controller, $request) {
		$item = $request['item'];
		$data = array();
		if (!$this->_audit($item)) {
			$data['status'] = 2;
		} else {
			$data['status'] = 1;
		}

		echo json_encode($data);
		return true;
	}

	function _audit($service) {
		if ($this->_is_admin()) {
			return true;
		}
		
		$emp = $_SESSION['id'];
		
		require_once(dirname(__FILE__) . '/emp/EmpService.class.php');
		$aa = new EmpService();
		
		return $aa->_audit($service, $emp);
	}
	
	function _list_email($service) {
		require_once(dirname(__FILE__) . '/emp/EmpService.class.php');
		$aa = new EmpService();
		
		return $aa->_list_email($service);
	}
	
	function _list_service($service) {
		require_once(dirname(__FILE__) . '/emp/EmpService.class.php');
		$aa = new EmpService();
		
		return $aa->_list($service);
	}
	
	function ajax_id($controller, $request) {
		$id = $this->_input($request['id']);
		
		// $row = $this->id($this->tbl, $id);
		$row = $this->_view($id);
		
		echo json_encode($row);
	}
	
	function _view($id = 0, $row = null) {
		
	}

	function ajax_oper($controller, $request) {
		$request['field'] = 'oper';

		$this->ajax_x($controller, $request);
		return true;
	}

	function ajax_emp($controller, $request) {
		$id = $_COOKIE['id_'];
		$ret = array();
		
		if ($this->_ajax_x($id, 'emp')) {
			$ret['status'] = 1;
		} else if ($this->_ajax_x($id, 'oper')) {
			$ret['status'] = 1;
		} else {
			$ret['status'] = 2;
		}

		echo json_encode($ret);
	}
	
	function ajax_emp_oper($controller, $request) {
		$id = $_COOKIE['id_'];
		$ret = array();
		
		if ($this->_ajax_x($id, 'emp')) {
			$ret['status'] = 1;
		} else if ($this->_ajax_x($id, 'oper')) {
			$ret['status'] = 1;
		} else {
			$ret['status'] = 2;
		}

		echo json_encode($ret);
	}

	function ajax_applicant($controller, $request) {
		$request['field'] = 'applicant';

		$this->ajax_x($controller, $request);
		return true;
	}

	function ajax_engineer($controller, $request) {
		$request['field'] = 'engineer';

		$this->ajax_x($controller, $request);
		return true;
	}

	function ajax_admin($controller, $request) {
		$request['field'] = 'admin';

		$this->ajax_x($controller, $request);
		return true;
	}

	function ajax_x($controller, $request) {
		$id = $_COOKIE['id_'];
		$field = $request['field'];

		$data = array();
		if (!$this->_ajax_x($id, $field)) {
			$data['status'] = 2;
		} else {
			$data['status'] = 1;
		}

		$controller->assign('result', json_encode($data));

		$request['tpl'] = 'json';
		$controller->display($request, 'json');
		return true;
	}

	function _ajax_x($id, $field) {
		if ($this->_is_admin()) {
			return true;
		}

		$db = newdb($this->tbl);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row[$field] == $_SESSION['id']) {
				return true;
			}
		}

		return false;
	}

	function ajax_createtime($controller, $request) {
		$id = $_COOKIE['id_'];
		$hour = $request['hour'];
		if (empty($hour)) {
			$hour = 8;
		}

		$data = array();
		if (!$this->_ajax_createtime($id, $hour)) {
			$data['status'] = 2;
		} else {
			$data['status'] = 1;
		}

		$controller->assign('result', json_encode($data));

		$request['tpl'] = 'json';
		$controller->display($request, 'json');
		return true;
	}

	function _ajax_createtime($id, $hour) {
		if ($this->_is_admin()) {
			return true;
		}

		$s = sprintf("-%s hour", $hour);

		$db = newdb($this->tbl);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			if (strtotime($row['createtime']) > strtotime($s)) {
				return true;
			}
		}

		return false;
	}
	
	function _ret_json($status) {
		$ret = array();		
		$ret['status'] = $status;

		echo json_encode($ret);
	}

	function _file($data) {
		$db = newdb(Constant::tbl_file);
		$fmt = "SELECT * FROM %s WHERE file = '%s' AND info = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_file, $this->file, $data['id']);
		// debug($sql);
		$result = $db->query($sql);

		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['file'] = Download::url($this->info_dir, $data['createtime'], $data['id'], $row['name']);
			$row['size_t'] = printsize($row['size']);

			$ret[] = $row;
		}

		return $ret;
	}

	function _file_exist($id) {
		$db = newdb(Constant::tbl_file);
		$fmt = "SELECT * FROM %s WHERE file = '%s' AND info = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_file, $this->file, $id);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	/**
	 * 修改状态
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ss($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$field = array(
			'-' => '请选择',
			'emp' => 'emp',
			'oper' => 'oper',
			'office' => 'office',
				
			'mold' => 'mold',
				
			'visible' => 'visible',
			'supplier' => 'supplier',
			'customer' => 'customer',			
		);

		$controller->assign_by_ref('field_option', $field);

		$controller->display($request, 'a/ss');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ssPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);

		$field = $request['field'];
		$data = $this->_input($request['data']);
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		if (empty($data)) {
			$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $status, $id);
		} else {
			$fmt = "UPDATE %s SET %s = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $field, $data, $status, $id);
		}
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$this->_ss_status($id, $status);
		
		$content = sprintf("%s=%s", $field, $data);		
		$this->_log_status($this->tbl, $id, $row['status'], $status, $content);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _ss_status($id, $status) {
		
	}
	
	function _log_status($tbl, $tbl_id, $from, $to, $content) {
		if (!empty($this->name)) {
			$name = $this->name;
		}
		
		$from_t = $this->status[$from];
		$to_t = $this->status[$to];
		
		$db = newdb('emp');
		$fmt = "INSERT INTO %s(tbl, tbl_id, name, `from`, `from_t`, `to`, `to_t`, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, Constant::tbl_status, $tbl, $tbl_id, $name, $from, $from_t, $to, $to_t, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
	}
	
	/**
	 * 批量更新
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function uu($controller, $request) {
		$this->pretreat($controller);

		$field = array(
			'-' => '请选择',
			'emp' => 'emp',
			'applicant' => 'applicant',
			'engineer' => 'engineer',
			'admin' => 'admin',
			'oper' => 'oper',
		);

		$controller->assign_by_ref('field_option', $field);

		$controller->display($request, 'a/uu');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function uuPost($controller, $request) {
		$this->pretreat($controller);

		$field = $request['field'];
		$data1 = $this->_input($request['data1']);
		$data2 = $this->_input($request['data2']);

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET %s = '%s' WHERE %s = '%s'";
		$sql = sprintf($fmt, $this->tbl, $field, $data2, $field, $data1);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _message($from, $to, $subject, $content) {
		$this->_notice($from, $to, $subject, $content);
	}

	function _notice($from, $to, $subject, $content, $html = 2) {
		$subject = addslashes($subject);
		$content = addslashes($content);
		
		$db = newdb('emp');
		$fmt = "INSERT INTO %s(`from`, `to`, subject, content, html, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, Constant::tbl_emp_notice, $from, $to, $subject, $content, $html);
		// debug($sql);
		$db->query($sql);
		
		$this->_jabber_send($from, $to, $subject);
	}

	function _dept($dept) {
		if (empty($dept)) {
			return '';
		}

		$key = "dept_" . $dept;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (!empty($ret)) {
				return $ret;
			}
		}

		$ret = $this->_dept_full($dept, '', 2);
		if (empty($ret)) {
			return '';
		}

		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	function _dept_full($dept, $ret, $len) {
		if (empty($dept)) {
			return $ret;
		}

		$a = substr($dept, 0, $len);
		$ret .= Name::dept($a);
		if (strlen($dept) <= $len) {
			return $ret;
		}

		$len += 2;

		return $this->_dept_full($dept, $ret, $len);
	}

	function _group2($controller, $sql) {
		$db = newdb($this->dsn_r);
		$result = $db->query($sql);
		debug($sql);

		$data = array();
		$count = 1;
		$xx = 0;
		$total = 0;
		$max_result = intval($this->result_s);
		while ($row = $db->fetch_array($result)) {
			$total += $row['c'];
			if ($count >= $max_result) {
				$xx += $row['c'];
				continue;
			}

			if ($row['c'] == 0) {
				continue;
			}

			$row = $this->_name($row, $this->groupby_s);
			$data[] = $row;
			$count++;
		}

		if ($xx > 0) {
			$data[] = array('a'=>'其它', 'c'=>$xx);
		}

		$aa = array();
		while (list($k, $v) = each($data)) {
			$v['p'] = number_format(($v['c'] / $total) * 100, 2, '.', '') . "%";

			if ($this->num_s == '2') {
				$v['c'] = $this->_num_t($v['c']);
			}

			$aa[] = $v;
		}

		if ($this->num_s == '2') {
			$total = $this->_num_t($total);
		}

		$a = array();
		$b = array();
		$c = array();
		reset($data);
		while (list($k, $v) = each($aa)) {
			$a[] = sprintf("%s %s", $v['a'], $v['p']);
			$b[] = $v['a'];
			$c[] = $v['c'];
		}
			
		$sa = join(",", $a);
		$sc = join(",", $c);
		
		$bar['a'] = join(",", $a);
		$bar['b'] = join(",", $b);
		$bar['c'] = join(",", $c);
		
		$controller->assign_by_ref('bar', $bar);

		$controller->assign_by_ref('total', $total);
		$controller->assign_by_ref('result', $aa);
	}
	
	function _group($controller, $request) {
		
		$sql = $request['sql'];
		
		$this->_group2($controller, $sql);
		
		$tpl = $request['tpl'];
		
		if ($tpl == 'xls') {
			$filename = sprintf("%s.xls", date("YmdHis"));
			header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);
		}
		
		if ($tpl == 'doc') {
			$filename = sprintf("%s.doc", date("YmdHis"));
			header('Content-Disposition:application/msword; filename=' . $filename);
		}
		
		$view = $request['view'];
		if ($view == 'print') {
			$controller->display($request, 'list_2');
		} else {
			$controller->display($request, 'list');
		}
	}
	
	function _tj_a($controller, $request) {	
		$s = $this->groupby($controller, $this->groupby_s);
		$df = "DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')";

		$fmt = "SELECT %s as a, COUNT(%s) as c FROM %s a WHERE createtime > %s GROUP BY %s ORDER BY c DESC";
		$sql = sprintf($fmt, $s, $s, $this->tbl, $df, $s);
		echo $sql . "\n";

		$this->_group_tj($controller, $sql);

		return $controller->sunxy($request, 'tj_a');
	}
	
	function _group_tj($controller, $sql) {
		$db = newdb($this->dsn_r);
		$result = $db->query($sql);

		$data = array();
		$count = 1;
		$xx = 0;
		$total = 0;
		$max_result = intval($this->result_s);
		while ($row = $db->fetch_array($result)) {
			$total += $row['c'];
			if ($count >= $max_result) {
				$xx += $row['c'];
				continue;
			}

			if ($row['c'] == 0) {
				continue;
			}

			$row = $this->_name($row, $this->groupby_s);
			$data[] = $row;
			$count++;
		}

		if ($xx > 0) {
			$data[] = array('a'=>'其它', 'c'=>$xx);
		}

		$aa = array();
		while (list($k, $v) = each($data)) {
			$v['p'] = number_format(($v['c'] / $total) * 100, 2, '.', '') . "%";

			if ($this->num_s == '2') {
				$v['c'] = $this->_num_t($v['c']);
			}

			$aa[] = $v;
		}

		if ($this->num_s == '2') {
			$total = $this->_num_t($total);
		}

		$controller->assign_by_ref('total', $total);
		$controller->assign_by_ref('result', $aa);
	}
	
	function _group_tj2($sql) {
		$db = newdb($this->dsn_r);
		$result = $db->query($sql);

		$data = array();
		$count = 1;
		$xx = 0;
		$total = 0;
		$max_result = intval($this->result_s);
		while ($row = $db->fetch_array($result)) {
			$total += $row['c'];
			if ($count >= $max_result) {
				$xx += $row['c'];
				continue;
			}

			if ($row['c'] == 0) {
				continue;
			}

			$row = $this->_name($row, $this->groupby_s);
			$data[] = $row;
			$count++;
		}

		if ($xx > 0) {
			$data[] = array('a'=>'其它', 'c'=>$xx);
		}

		$aa = array();
		while (list($k, $v) = each($data)) {
			$v['p'] = number_format(($v['c'] / $total) * 100, 2, '.', '') . "%";

			if ($this->num_s == '2') {
				$v['c'] = $this->_num_t($v['c']);
			}

			$aa[] = $v;
		}

		if ($this->num_s == '2') {
			$total = $this->_num_t($total);
		}

		$ret['data'] = $aa;
		$ret['total'] = $total;
		
		return $ret;
	}

	function _num_t($t) {
		return $t;
	}

	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$fmt = "SELECT %s AS a, COUNT(*) AS c FROM %s a %s GROUP BY %s ORDER BY %s %s";
		$where = $this->_where($request);
		$request['sql'] = sprintf($fmt, $this->s, $this->tbl, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}
	
	function _office($id) {
		if (empty($id)) {
			return '';
		}
		
		$row = Common::id(Constant::tbl_emp, $id);
		
		return $row['office'];
	}
	
	function _emp_dept($id) {
		if (empty($id)) {
			return '';
		}
		
		$row = Common::id(Constant::tbl_emp, $id);
		
		return $row['dept'];
	}
	
	function _emp_exten($id) {
		if (empty($id)) {
			return '';
		}
		
		$row = Common::id(Constant::tbl_emp, $id);
		
		return $row['exten'];
	}
	
	function _emp_email($id) {
		if (empty($id)) {
			return '';
		}
		
		$row = Common::id(Constant::tbl_emp, $id);
		
		return $row['email'];
	}
	
	function _emp_mobile($id) {
		if (empty($id)) {
			return '';
		}
		
		$row = Common::id(Constant::tbl_emp, $id);
		
		return $row['mobile'];
	}
	
	function _exchange($code) {
		$key = "exchange.ajax_" . $code;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (!empty($ret)) {
				return $ret;
			}
		}
		
		$db = newdb('fy');		
		$fmt = "SELECT * FROM %s WHERE type = '1' AND code = '%s'";
		$sql = sprintf($fmt, Constant::tbl_tec, $code);		
		// debug($sql);
		$result = $db->query($sql);
		$ret = "1.0";
		if ($row = $db->fetch_array($result)) {
			$ret = $row['data'];
		}
		
		if (is_object($mc) && !empty($ret)) {
			$mc->set($key, $ret, 0, _strtotime("15 minute"));
		}
		
		return $ret;
	}
	
	function am($exten) {
		if (preg_match("/^6\d{3}/i", $exten)) {
			return astman('ns');
		}

		if (preg_match("/^8\d{3}/i", $exten)) {
			return astman('sj');
		}

		if (preg_match("/^2\d{3}/i", $exten)) {
			return astman('qx');
		}

		return false;
	}
	
	function am_sql($exten) {
		if (preg_match("/^6\d{3}/i", $exten)) {
			return newdb('ns11');
		}
	
		if (preg_match("/^8\d{3}/i", $exten)) {
			return newdb('sj11');
		}
	
		if (preg_match("/^2\d{3}/i", $exten)) {
			return newdb('qx11');
		}
	
		return false;
	}

	function am_close($am) {
		if (!$am) {
			return false;
		}

		$am->disconnect();
	}
	
	function _format($s, $step, $split) {
		$s = str_replace(' ', '', $s);
		$len = strlen($s);
		
		if ($len > $step) {
			$i = 0;

			$arr = array();
			while ($i < $len) {
				$ss = substr($s, $i, $step);
				
				$arr[] = $ss;
				$i += $step;
			}
			
			return implode(" ", $arr);
		} else {
			return $s;
		}		
	}
	
	function _shift($a) {
		$ret = array();
		while (list($k, $v) = each($a)) {
			if ($k == '-') {
				continue;
			}
			
			$ret[$k] = $v;
		}
		
		return $ret;
	}
	
	/**
	 * 人民币小写转大写
	 * 
	 * @param $RMB
	 * @param $Format
	 * @return string
	 */	
	function rmb2($RMB = 0, $Format = '') {
		if (eregi ( "[^0-9.]", $RMB )) {
			return "";
		}
		
		if ($RMB == 0) {
			if ($Format != 0)
				$GLOBALS [$Format] = "0.00";
				return "零元整";
            }

			$re = '';
			$arr1 = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' );
			$arr2 = array('', '<span>拾</span>', '<span>佰</span>', '<span>仟</span>', '<span>元</span>', '<span>万</span>', '<span>亿</span>' );
			//要适合打印模板，将arr2的值用空格代替
			//$arr2 = array('','  ','  ','  ','元','  ','  ');
			
			$arr3 = array('<span>角</span>', '<span>分</span>', '<span>厘</span>', '<span>毫</span>' );
			$pre2 = count( $arr3 ); //小数位最大精确度 precision
			$arr = explode( ".", $RMB ); //按小数点切割金额
			
			$len1 = strlen( $arr [0] ); //整数位长度
			$len2 = isset( $arr [1] ) ? strlen ( $arr [1] ) : 0; //小数位长度
			
			for ($i = 0; $i < $len1; $i ++) {
				$bit = $arr [0] [$len1 - $i - 1]; //当前位小写金额
				$cn = $arr1 [$bit]; //当前位大写金额
				if ($i == 0) {
					$unit = $arr2 [4]; //当前位金额单位 元
				} elseif ($i % 8 == 0) {
					$unit = $arr2 [6]; //当前位金额单位 亿
				} elseif ($i % 4 == 0) {
					$unit = $arr2 [5]; //当前位金额单位 万
				} else {
					$unit = $arr2 [$i % 4]; //当前位金额单位 '拾','佰','仟'
				}
				
				//小写金额为零的情况
				if ($bit == 0) {
					if (ereg ( '元|万|亿', $unit )) {
						$re = $unit . $re;
					} else {
						$re = $cn . $re;
					}
				} //小写金额非零的情况 
				else {
					$re = $cn . $unit . $re;
				}
			}
			
			for ($i = 0; $i < count ( $arr3 ) && $i < $len2; $i ++) {
				$bit = $arr [1] [$i]; //当前位小写金额
				$cn = $arr1 [$bit]; //当前位大写金额
				$unit = $arr3 [$i]; //当前位金额单位
				if ($bit != 0) {
					$re .= $cn . $unit;
				} elseif ($i < 2) {
					$re .= "零";
				}
			}
			
			if ($Format) { //格式化小写金额
				$format = '';
				$gage = min ( max ( 2, $len2 ), $pre2 ); //小数部分的精确位数。不小于2，不大于最大精确度
				
				if ($arr [0] == 0) {
					$format .= '0';
				} else {
					while ( $arr [0] != '' ) {
						$format = ($arr [0] > 999 ? "," : "") . substr ( $arr [0], - 3 ) . $format;
						$arr [0] = substr ( $arr [0], 0, - 3 );
					}
				}
				$format .= "." . @substr ( $arr [1] . '00', 0, $gage );
				$GLOBALS [$Format] = $format;
			}
			
			$re = preg_replace ( array ("/亿万/", "/(零){2,}/", "/^(元零|元)|(零)$/", "/零(亿|万|元)/" ), array ("亿", "零", "", "\1" ), $re ); //正则替换
			if (! $len2) {
				$re .= "整"; //当没有小数位时加上“整”
			}
			
		return $re;
	}
	
	function rmb($s) {
		$s = abs($s);
		$ret = "零元整";
		if (eregi("[^0-9.]", $s)) {
			return $ret;
		}
		
		if ($s == 0 || $s == "") {			
			return $ret;
        }
        
        $digits = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
		$radices = array("", '拾', '佰', '仟',);
		$bigRadices = array("", '万', '亿');
		$decimals = array('角', '分', '厘', '毫');
		
		$arr = explode(".", $s); 	//按小数点切割金额
		
		// print_r($arr);
		
		$len1 = strlen($arr[0]); 	//整数位长度
		$len2 = isset($arr[1]) ? strlen($arr[1]) : 0; //小数位长度
		
		// echo sprintf("%s %s\n", $len1, $len2);
		
		$zeroCount = 0;
		
		$ret = "";
		// Process integral part if it is larger than 0:
		if (intval($arr[0]) > 0) {
			$zeroCount = 0;
			for ($i = 0; $i < $len1; $i++) {
				$p = $len1 - $i - 1;
				$d = substr($arr[0], $i, 1);
				// echo sprintf("%s %s\n", $p, $d);
				
				$quotient = $p / 4;
				$quotient = floor($p / 4);
				$modulus = $p % 4;
				
				// echo sprintf("quotient = %s, modules = %s\n", $quotient, $modulus);
				if ($d == "0") {
					$zeroCount++;
				} else {
					if ($zeroCount > 0) {
						$ret .= $digits[0];
					}
					$zeroCount = 0;
					$ret .= $digits[intval($d)] . $radices[$modulus];
				}
				
				if ($modulus == 0 && $zeroCount < 4) {
					$ret .= $bigRadices[$quotient];
				}
			}
			
			$ret .= "元";
		}
		
		// Process decimal part if there is:
		if ($len2 > 0) {
			$decimal = $arr[1];
			for ($i = 0; $i < $len2; $i++) {
				$d = substr($arr[1], $i, 1);
				if ($d != "0") {
					$ret .= $digits[intval($d)] . $decimals[$i];
				} else {
					$ret .= "零";
				}
			}
		} else {
			$ret .= "整";
		}
					
		return $ret;
	}
	
	function _supplier_x($id) {
		require_once(dirname(__FILE__) . '/info/Contact.class.php');
		$aa = new Contact();
		
		$c = $aa->_linkman_primary("2", $id);
		
		$ret['contact'] = $c['name'];
		$ret['mobile'] = $c['mobile'];
		$ret['tel'] = $c['tel'];
		$ret['fax'] = $c['fax'];
		$ret['email'] = $c['email'];
		$ret['content'] = $c['content'];
		
		$ret = json_encode($ret);
		
		return addslashes($ret);
	}
	
	function _customer_x($id) {
		require_once(dirname(__FILE__) . '/info/Contact.class.php');
		$aa = new Contact();
		
		$c = $aa->_linkman_primary("1", $id);
		
		$ret['contact'] = $c['name'];
		$ret['mobile'] = $c['mobile'];
		$ret['tel'] = $c['tel'];
		$ret['fax'] = $c['fax'];
		$ret['email'] = $c['email'];
		$ret['content'] = $c['content'];
		
		$ret = json_encode($ret);
		
		return addslashes($ret);
	}
	
	function _zjm_clean($s) {
		if (empty($s)) {
			return false;
		}
		
		$s = strtolower($s);
		for ($i = 1; $i <= strlen($s); $i++) {
			$q = substr($s, 0, $i);
			$key = sprintf("%s_%s_%s", $this->zjm, $this->tbl, $q);
			
			debug($key);
			clean($key);
		}
		
		return true;
	}
	
	function _emp_x($id) {
		$row = Common::id(Constant::tbl_emp, $id);
		
		// $row['office_t'] = $this->office[$row['office']];
		// $row['dept_t'] = $this->_dept($row['dept']);
		
		return $row;
	}
	function _view_t($row) {		
		if (!empty($row['emp'])) {
			$row['emp_x'] = $this->_emp_x($row['emp']);
			if ($row['emp_x']['status'] == '1') {
				$row['emp_t'] = $row['emp_x']['name'];
			} else {
				$row['emp_t'] = sprintf("%s%s", $row['emp_x']['name'], $row['emp_x']['status']);
			}
		}
		
		if (!empty($row['oper'])) {
			$emp = Common::id(Constant::tbl_emp, $row['oper']);
			
			if ($emp['status'] == '1') {
				$row['oper_t'] = $emp['name'];
			} else {
				$row['oper_t'] = sprintf("%s%s", $emp['name'], $emp['status']);
			}
		}
		
		if (!empty($row['office'])) {
			$row['office_t'] = $this->office[$row['office']];
			$row['company_t'] = $this->_company($row['office']);
		}
		
		if (!empty($row['dept'])) {
			$row['dept_t'] = $this->_dept($row['dept']);
		}
		
		if (!empty($row['mold'])) {
			$row['mold_t'] = Name::mold($row['mold']);
		}
		
		if (!empty($row['supplier'])) {
			$row['supplier_t'] = Name::supplier($row['supplier']);
		}
		
		if (!empty($row['currency'])) {
			$row['currency_t'] = $this->currency[$row['currency']];
		}
				
		if (!empty($row['status'])) {
			$row['status_t'] = $this->status[$row['status']];
		}
		
		return $row;
	}
	
	function _company($office) {
		/*
		if ($office == '1' || $office == '2') {
			return '景荣精密产品（深圳）有限公司';
		}
		
		if ($office == '3') {
			return '广东景荣产品有限公司';
		}*/
		
		return '深圳一点通网络科技有限公司';
	}
	
	function is_utf8($string) {
		return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
	}
	
	function _to_utf8($s) {
		$s = trim($s);
		if ($this->is_utf8($s)) {
			return $s;
		}
		
		return iconv("GBK", "UTF-8", $s);
	}
	
	function _tab($a) {
		$b = array(			
			// '我的电话' => array('cc'=>'my.php?do=MyTel.find', 'js'=>''),
			// '我的通知' => array('cc'=>'my.php?do=MyNotice.find', 'js'=>''),

			'我的定制' => array('cc'=>'info.php?do=CustomizeMy.tab', 'js'=>''),
		);
				
		$data = array_merge($a, $b);
		$ret = array();
		while (list($k, $v) = each($data)) {
			if ($this->tree_my($v)) {
				$v['dd'] = str_replace("", "/t/mobile/", $v['cc']);
				debug(print_r($v, true));
				
				$ret[$k] = $v; 
			}
		}
		
		return $ret;
	}
	
	function _tab2($a) {
		$ret = array();
		while (list($k, $v) = each($a)) {
			if (array_key_exists('v', $v) && $v['v'] == '1') {
				$ret[$k] = $v;
			} elseif ($this->tree_my($v)) {
				$v['dd'] = str_replace("", "/t/mobile/", $v['cc']);
				debug(print_r($v, true));
	
				$ret[$k] = $v;
			}
		}
	
		return $ret;
	}
	
	function _tj_bb($controller, $aa) {
		$data = array();
		while (list($k, $v) = each($aa)) {
			$row = $this->_tj2($v);
			if (count($row['data']) == 0) {
				continue;
			}
			
			$row['title'] = $k;
			
			$data[] = $row;
		}
				
		$controller->assign_by_ref('result', $data);
	}
	
	function _tj_list($a) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE %s ORDER BY %s";		
		$sql = sprintf($fmt, $this->tbl, $a['w'], $a['b']);
		// echo $sql . "\n";
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
		
			$data[] = $row;
		}
		
		$ret['data'] = $data;
		
		return $ret;
	}
	
	function _tj_cc($controller, $cc) {
		$list = array();
		$i = 0;
		while (list($k, $v) = each($cc)) {
			$row = $this->_tj_list($v);
			if (count($row['data']) == 0) {
				continue;
			}
						
			$row['title'] = $k;
			
			$list[] = $row;
			$i += count($row['data']);
		}
		
		if ($i == 0) {
			return true;
		}
		
		$controller->assign_by_ref('list', $list);
		
		return false;
	}
	
	function _tj_html($controller, $request, $tpl) {
		$request['tpl'] = "html4";
		
		return $controller->sunxy($request, $tpl);
	}
	
	function _tj_mail($from, $bb, $subject, $body) {
		if (!$bb || count($bb) == 0) {
			return;
		}
		
		while (list($k, $to) = each($bb)) {
			// $to = '997264@qq.com';
			echo $to . "\n";
			$this->mail_html($from, $to, $subject, $body);
		}
	}
	
	function _tj_df($d, $f) {
		$fmt = "DATE_FORMAT(%s, '%s') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%s')";
		
		return sprintf($fmt, $d, $f, $f);
	}
	
	function _tj_df_not($f) {
		$fmt = "DATE_FORMAT(createtime, '%s') <> DATE_FORMAT(modifytime, '%s')";
		
		return sprintf($fmt, $f, $f);
	}
	
	function ping($host) {
		require_once "Net/Ping.php";
		$ping = Net_Ping::factory();

		if (PEAR::isError($ping)) {
			echo $ping->getMessage();
		} else {
			$ping->setArgs(array('count' => 3, 'timeout' => 3));
			$raw = $ping->ping($host);
			
			// print_r($raw);
			if ($raw->_received == 3) {
				return true;
			}
		}
		
		return false;
	}
	
	function printtime($time) {
		$minute = floor($time / 60);
		$second = $time % 60;

		return sprintf("%02d:%02d", $minute, $second);
	}
	
	function _is_admin() {
		if ($_SESSION['admin'] == "8") {
			return true;
		}
		
		return false;
	}
	
	function _item_blank($len = 5, $v = array("ok"=>true)) {
		$ret = array();
		$i = 0;
		for ($i = 0; $i < $len; $i++) {
			$ret[] = $v;
		}
		
		return $ret;
	}
		
	function date_diff($part, $begin, $end) {
		if (empty($begin) || empty($end)) {
			return '';
		}
		
		$diff = strtotime($end) - strtotime($begin);
		
		$ret = 0;
		switch ($part) {
			case "y": 
				$a = 60 * 60 * 24 * 365; 
				break;
			case "m": 
				$a = 60 * 60 * 24 * 30; 
				break;
			case "w": 
				$a = 60 * 60 * 24 * 7; 
				break;
			case "d": 
				$a = 60 * 60 * 24; 
				break;
			case "h": 
				$a = 60 * 60; 
				break;
			case "n": 
				$a = 60; 
				break;
			case "s": 
				$ret = $diff; 
				break;
		}
		
		if ($part == '' || $part == 's') {
			return $diff;
		}
		
		$ret = $diff / $a; 

		return $ret;
	}
	
	function ajax_linkman($controller, $request) {
		$q = $this->_input($request['q']);
	
		require_once(dirname(__FILE__) . '/info/Contact.class.php');
		$aa = new Contact();
	
		$data = $aa->_ajax_linkman(2, $q);
		echo json_encode($data);
	}
	
	function ajax_linkman1($controller, $request) {
		$q = $this->_input($request['q']);
	
		require_once(dirname(__FILE__) . '/info/Contact.class.php');
		$aa = new Contact();
	
		$data = $aa->_ajax_linkman(1, $q);
		echo json_encode($data);
	}
	
	function tecmold() {
		require_once(dirname(__FILE__) . '/contact/Customer.class.php');
		$aa = new Customer();
	
		return $aa->tecmold();
	}
	
	function _has_vacation($emp) {
		require_once(dirname(__FILE__) . '/../../admin/lib/kq/Vacation.class.php');
		$vacation = new Vacation();
	
		return $vacation->_has_vacation($emp);
	}
	
	function _audit_office($p) {
		$ret = array();
		
		while (list($k, $v) = each($p)) {
			if ($this->_audit($v)) {
				$ret[] = $k;
			}
		}
		
		return $ret;
	}
	
	function _jabber_send($from, $to, $message) {
		require_once(dirname(__FILE__) . '/jabber/Jabber.class.php');
		$jabber = new Jabber();
		
		$jabber->_send($from, $to, $message);
	}
	
	function _list_mold($id, $status = 'all', $num = 20) {
		$ret = array();
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `mold` = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $num);
		} else {
			$fmt = "SELECT * FROM %s WHERE `mold` = '%s' AND status = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $status, $num);
		}
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$ret[] = $row;
		}
	
		return $ret;
	}
	
	function _list_customer($id, $status = 'all', $num = 20) {
		$ret = array();
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `customer` = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $num);
		} else {
			$fmt = "SELECT * FROM %s WHERE `customer` = '%s' AND status = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $status, $num);
		}
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$ret[] = $row;
		}
	
		return $ret;
	}
	
	function _list_supplier($id, $status = 'all', $num = 20) {
		$ret = array();
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `supplier` = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $num);
		} else {
			$fmt = "SELECT * FROM %s WHERE `supplier` = '%s' AND status = '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $id, $status, $num);
		}
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$ret[] = $row;
		}
	
		return $ret;
	}
	
	function _my() {
		return '';
	}
	
	function _list_emp($id, $status = 'all', $num = 20) {
		$ret = array();
		
		$my = $this->_my();
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `emp` = '%s' ";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `emp` = '%s' AND status = '%s' ";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		
		$orderby = sprintf(" ORDER BY id DESC LIMIT %s", $num);
		
		if (!empty($my)) {
			$sql .= ' AND ' . $my;
		}
		
		$sql .= $orderby;
		
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$ret[] = $row;
		}
	
		return $ret;
	}
	
	function _name_t($row, $px) {
		
		if ($px == 'office') {
			$row['a'] = $this->office[$row['a']];
		} elseif ($px == 'dept') {
			$row['a'] = $this->_dept($row['a']);
		} elseif ($px == 'emp' || $px == 'oper' || $px == 'worker') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'mold') {
			$row['a'] = sprintf("%s [%s]", Name::mold($row['a']), $row['a']);
		} elseif ($px == 'customer') {
			$row['a'] = Name::customer_code($row['a']);
		} elseif ($px == 'supplier') {
			$row['a'] = sprintf("%s [%s]", Name::supplier($row['a']), $row['a']);
		} elseif ($px == 'type') {
			$row['a'] = $this->type[$row['a']];
		} elseif ($px == 'currency') {
			$row['a'] = $this->currency[$row['a']];
		} elseif ($px == 'status') {
			$row['a'] = $this->status[$row['a']];
		}
	
		return $row;
	}
	
	function ajax_upload2($controller, $request) {
		
		if (empty($this->tbl)) {
			return false;
		}
		
		if (!class_exists("MogileFs")) {
			return false;
		}
		
		$id = $request['id'];
		$oper = $request['oper'];
		
		$this->_files_clean($id);
	
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
	
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			// die($file->getMessage());
			debug($file->getMessage());
		}
	
		if ($file->isValid()) {
			$filename = $file->getProp("tmp_name");
			
			$name = $file->getProp('name');
			$ext = $file->getProp('ext');
			// $s = sprintf("name = %s, ext = %s", $name, $ext);
			$rnd = rand(100,1000);
			// debug($s);
	
			$mg = newfs('ydt');
	
			$key = sprintf("%s_%s_%s_%s_%s.%s", $this->tbl, $id, $oper, time(), $rnd, $ext);
			
			$key = strtolower($key);
			
			try {
				$s = sprintf("key = %s, filename = %s\n", $key, $filename);
				debug($s);
					
				$mg->put($filename, $key, 'upload');
				$mg->close();
			} catch(MogileFsException $e) {
				debug($e);
			}
		}
	
		echo "1";
		return true;
	}
	
	function download($controller, $request) {
	
		$key = $request['key'];
	
		if (empty($key)) {
			return false;
		}
		
		if (!class_exists("MogileFs")) {
			return false;
		}
	
		$ret = false;
		$mg = newfs('ydt');
		try {
				
			$paths = $mg->get($key);
	
			$url = $paths['path1'];
			
			// require_once(dirname(__FILE__) . '/core/FileType.class.php');

			// $ext = FileType::getFileType($url);
			$ext = end(explode('.', $key));
			
			$mime = $this->mime[$ext];
			
			$rnd = rand(100, 1000);
			
			// $filename = sprintf("%s_%s.%s", time(), $rnd, $ext);
			$filename = $key;
			
			// $mime = "image/jpeg";
			
			$s = sprintf('Content-Disposition:%s; filename=%s', $mime, $filename);
			debug($s);
			
			header($s);
			echo file_get_contents($url);
	
		} catch(MogileFsException $e) {
			debug($e);
		}
	}
	
	function file($controller, $request) {
	
		$key = $request['key'];
	
		if (empty($key)) {
			return false;
		}
		/*
		if (!$this->_file_delete($key)) {
			return false;
		}*/
	
		if (!class_exists("MogileFs")) {
			return false;
		}
	
		$ret = false;
		$mg = newfs('ydt');
		try {
	
			$ret = $mg->delete($key);
	
		} catch(MogileFsException $e) {
			debug("error");
		}
		
		preg_match('/([a-z|_|\\.]+)(_)(\d+)/', $key, $a);
		$key = sprintf("%s_mg", $a[0]);
		clean($key);
	
		echo $ret;
	}
	
	function _file_delete($key) {
		if (empty($key)) {
			return false;
		}
		
		if ($this->_is_admin()) {
			return true;
		}
		
		// $a = preg_split("/(_)/", $key);
		preg_match('/(_)(\d+)(_)(\d+)/', $key, $a);
		debug(print_r($a, true));
		
		$emp = $_SESSION['id'];
		
		if (!empty($emp) && $a[4] == $emp) {
			return true;
		}
		
		return false;
	}
	
	function _files($id, $cache = true) {
		$key = sprintf("%s_%s_mg", $this->tbl, $id);
		
		$mc = memcache("root");
		if (is_object($mc) && $cache) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}
		
		$ret = $this->_files_get($id);
		
		// if (is_object($mc) && count($ret) > 0) {
		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("2 hour"));
		}
		
		return $ret;
	}
	
	function _files_clean($id) {
		$key = sprintf("%s_%s_mg", $this->tbl, $id);
		
		clean($key);
	}
	
	function _files_get($id) {
		
		$ret = array();
		
		if (empty($this->tbl)) {
			return $ret;
		}
		
		if (!class_exists("MogileFs")) {
			return $ret;
		}
		
		$prefix = sprintf("%s_%s_", $this->tbl, $id);
		
		try {
			$mg = newfs('ydt');
			$a = $mg->listKeys($prefix, '');
				
			$b = array();
			while (list($k, $key) = each($a)) {
				if (!preg_match("/^(key_)(\d+)$/i", $k)) {
					continue;
				}
	
				$b['key'] = $key;
				$paths = $mg->get($key);
				$b['url'] = $paths['path1'];
				
				if (preg_match("/(jpg|gif|png)$/i", $key)) {
					$b['type'] = 'image';
				}  else {
					$b['type'] = '';
				}
				
				$b = $this->_view_key($b, $key);
				
				$b = $this->_view_t($b);
	
				$ret[] = $b;
			}
	
		} catch(MogileFsException $e) {
			debug("error");
		}
	
		return $ret;
	}
	
	function _view_key($b, $key) {
		preg_match('/(_)(\d+)(_)(\d+)(_)(\d+)/', $key, $a);
		
		$b['emp'] = $a[4];
		$b['createtime'] = date('Y-m-d H:i:s', $a[6]);
		
		return $b;
	}
	
	function view_file($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
	
		$files = $this->_files($id);
		
	
		$controller->assign_by_ref('result', $files);
		
		$a = array(
			'fy.emp' => 'emp.php?do=Emp.download',
			'fy.customer' => 'contact.php?do=Customer.download',
			'fy.mold' => 'mold.php?do=Mold.download',
			'fy.supplier' => 'contact.php?do=Supplier.download',
		);
		
		$url = $a[$this->tbl];
		
		$controller->assign_by_ref('url', $url);
	
		$controller->display($request, 'file');
		return true;
	}
	
	function alpha2num($char) {
		$char = strtolower($char);
	
		$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		$len = strlen($char);
		for ($i = 0; $i < $len; $i++) {
			$index = array_search($char[$i], $array);
			$sum += ($index+1) * pow(26, $len - $i - 1);
		}
	
		return $sum - 1;
	}
	
	function get_alpha($a, $c) {
		$i = $this->alpha2num($c);
		$s = $a[$i];
		
		$s = trim($s);
		if (empty($s)) {
			return '';
		}
	
		// $s = preg_replace("/[\s|\"|\'|,|-]+/i", "", $s);
		$s = preg_replace("/[\"|\'|,|-]+/i", "", $s);
	
		return $s;
	}
	

	function _idcard($idcard) {
		$idcard = trim($idcard);
	
		$len = strlen($idcard);
		if ($len == 15 || $len == 18) {
			$identity = substr($idcard, 0, 6);
			$ret = $this->_idcard_region($identity);
	
			$len = strlen($idcard);
			if ($len == 15) {
				return $this->_idcard_15($ret, $idcard);
			}
	
			if ($len == 18) {
				return $this->_idcard_18($ret, $idcard);
			}
		}
	
		return false;
	}
	
	function _idcard_region($identity) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT province, city, region FROM %s WHERE identity = '%s'";
		$sql = sprintf($fmt, Constant::tbl_region, $identity);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return $db->fetch_array($result);
		}
	
		return false;
	}
	
	function _idcard_15($ret, $idcard) {
		$a = substr($idcard, 14, 1);
		$b = "19" . substr($idcard, 6, 6);
	
		$c = fmod($a, 2);
		$ret['sex'] = $c > 0 ? 1 : 2;
		$ret['birthday'] = date("Y-m-d", strtotime($b));
	
		return $ret;
	}
	
	function _idcard_18($ret, $idcard) {
		$a = substr($idcard, 16, 1);
		$b = substr($idcard, 6, 8);
	
		$c = fmod($a, 2);
		$ret['sex'] = $c > 0 ? 1 : 2;
		$ret['birthday'] = date("Y-m-d", strtotime($b));
	
		return $ret;
	}
	
	function week($date) {
		$i = date("w", strtotime($date));
		$a = array(
				'0' => '周日',
				'1' => '周一',
				'2' => '周二',
				'3' => '周三',
				'4' => '周四',
				'5' => '周五',
				'6' => '周六',
		);
	
		return $a[$i];
	}
	
	function ajax_upload($controller, $request) {
	
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}
	
		if ($file->isValid()) {
			$filename = $file->getProp("tmp_name");
	
			$id = $request['id'];
			$key = sprintf("%s_photo_%s", $this->tbl, $id);
	
			$mg = newfs('ydt');
			try {
				$mg->put($filename, $key, 'upload');
				$mg->close();
			} catch(MogileFsException $e) {
				debug("error");
			}
		}
	
		echo "1";
		return true;
	}
	
	function _photo($data) {
	
		if (!class_exists("MogileFs")) {
			return false;
		}
	
		$mg = newfs('ydt');
	
		$key = sprintf("%s_photo_%s", $this->tbl, $data['id']);
	
		try {
			$paths = $mg->get($key);
			$ret = $paths['path1'];
			$mg->close();
		} catch(MogileFsException $e) {
			$ret = '/images/photo.jpg';
		}
	
		return $ret;
	}
	
	function _customer($mold) {
		$m = split("\.|-", $mold);
	
		return $m[0];
	}
	
	function _project($mold) {
		$m = split("\.|-", $mold);
	
		return sprintf("%s.%s", $m[0], $m[1]);
	}
	
	function _project_m($mold) {
		$mold_t = Name::mold($mold);
		if (empty($mold_t)) {
			return '';
		}
		
		return $this->_project($mold_t);
	}
	
	function prj($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s ";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$mold_t = Name::mold($row['mold']);
			$project = $this->_project($mold_t);
	
			$fmt = "UPDATE %s SET project = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $project, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
	
		logdate($controller, $request);
		return true;
	}
	
	function _ok($s) {
		
		if ($s == 'true' || $s == '1') {
			debug("3150");
			return true;
		}
		
		if (empty($s) || $s == 'false' || $s == '0') {
			debug("3155");
			return false;
		}
		
		debug("3159");
		return false;
	}
	
	function http_post_data($url, $data_string) {
	
		$header = array(
			'Content-Type: application/json; charset=utf-8',
			'Content-Length: ' . strlen($data_string)
		);
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	
		ob_start();
		curl_exec($ch);
		$content = ob_get_contents();
		ob_end_clean();
	
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$ret = array($code, $content);
	
		return $ret;
	}
}
?>
